package com.zzt.config;

import com.zzt.entity.Memberinfo;
import com.zzt.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


//AOP:拦截器
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级安全验证
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    MyUserDetailService myUserDetailService;

    //链式变成
    //授权请求
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问  功能也只有对应权限的人才能访问
        http.authorizeRequests()
                .antMatchers("/").permitAll()  //首页所有人可以访问
                .antMatchers("/user/**").hasRole("LOGED")

                .and()
                .formLogin()                  //未授权跳转:以表单形式提交
                .loginPage("/loginPage.html")   //指定登录页:用户没认证跳转的页面
                .permitAll()
                //出现问题：bug :没走/login逻辑 没有保存
                .loginProcessingUrl("/login")   //指定登录地址 覆盖loginPage设置的默认值POST
                .permitAll()                    //登录地址本身也需要允许

//                .defaultSuccessUrl("/index.html")//登陆成功后跳转地址
                .usernameParameter("nickname")  //自己设置登录账号和密码
                .passwordParameter("pwd")

                .and()
                .csrf().disable()                   //禁用
        ;


        //无权限默认到登录页
//        http.formLogin();
    }

//    @Bean
//    public PasswordEncoder passwordEncoder(){
//        // 使用BCrypt加密密码
//        return new BCryptPasswordEncoder();
//    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        /*auth
            .inMemoryAuthentication()
            .passwordEncoder(encoder)
            .withUser("kk")
                .password(encoder.encode("kk")).roles("loged");
*/
        //认证规则里的用户从我们自定义的MyUserDetailService里读取，并用BCryptPasswordEncoder加密

        auth.userDetailsService(myUserDetailService)
                .passwordEncoder(encoder)
        ;
    }
}
